// 全局变量
let graphData = { nodes: [], relationships: [] };
let svg, simulation, link, node, nodeLabels, linkLabels;
let selectedNodes = [];
let width, height;

// 颜色配置
const nodeColors = {
    'Person': '#ff6b6b',
    'Company': '#4ecdc4', 
    'Project': '#45b7d1',
    'default': '#95a5a6'
};

// 初始化应用
document.addEventListener('DOMContentLoaded', function() {
    initializeGraph();
    bindEvents();
    updateConnectionStatus();
    loadGraphData();
});

// 初始化图谱
function initializeGraph() {
    const container = document.getElementById('graph');
    const rect = container.parentElement.getBoundingClientRect();
    width = rect.width;
    height = rect.height;
    
    svg = d3.select('#graph')
        .attr('width', width)
        .attr('height', height);
    
    // 创建力导向图模拟
    simulation = d3.forceSimulation()
        .force('link', d3.forceLink().id(d => d.id).distance(100))
        .force('charge', d3.forceManyBody().strength(-300))
        .force('center', d3.forceCenter(width / 2, height / 2))
        .force('collision', d3.forceCollide().radius(30));
}

// 绑定事件
function bindEvents() {
    document.getElementById('refreshBtn').addEventListener('click', loadGraphData);
    document.getElementById('initDataBtn').addEventListener('click', initSampleData);
    document.getElementById('addNodeBtn').addEventListener('click', showAddNodeModal);
    document.getElementById('searchBtn').addEventListener('click', searchNodes);
    document.getElementById('executeQueryBtn').addEventListener('click', executeCypherQuery);
    document.getElementById('settingsBtn').addEventListener('click', showSettingsModal);
    document.getElementById('testConnectionBtn').addEventListener('click', testConnection);
    
    // 搜索回车事件
    document.getElementById('searchInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            searchNodes();
        }
    });
    
    // 模态框事件
    document.querySelectorAll('.close').forEach(closeBtn => {
        closeBtn.addEventListener('click', function() {
            this.closest('.modal').style.display = 'none';
        });
    });
    
    // 表单提交事件
    document.getElementById('addNodeForm').addEventListener('submit', createNode);
    document.getElementById('addRelationshipForm').addEventListener('submit', createRelationship);
    document.getElementById('settingsForm').addEventListener('submit', saveSettings);
    
    // 点击模态框外部关闭
    window.addEventListener('click', function(event) {
        if (event.target.classList.contains('modal')) {
            event.target.style.display = 'none';
        }
    });
    
    // 窗口大小调整
    window.addEventListener('resize', handleResize);
}

// 加载图谱数据
async function loadGraphData() {
    showLoading(true);
    try {
        const response = await fetch('/api/graph/data');
        const result = await response.json();
        
        if (result.success) {
            graphData = result.data;
            updateGraph();
            updateStats();
            showNotification('数据加载成功', 'success');
        } else {
            throw new Error(result.message || '加载数据失败');
        }
    } catch (error) {
        console.error('加载数据失败:', error);
        showNotification('加载数据失败: ' + error.message, 'error');
    } finally {
        showLoading(false);
    }
}

// 更新图谱显示
function updateGraph() {
    if (!graphData.nodes || graphData.nodes.length === 0) {
        svg.selectAll('*').remove();
        return;
    }
    
    // 清除现有元素
    svg.selectAll('*').remove();
    
    // 创建连线
    link = svg.append('g')
        .attr('class', 'links')
        .selectAll('line')
        .data(graphData.relationships)
        .enter().append('line')
        .attr('class', 'link')
        .attr('stroke', '#999')
        .attr('stroke-opacity', 0.6)
        .attr('stroke-width', 2);
    
    // 创建节点
    node = svg.append('g')
        .attr('class', 'nodes')
        .selectAll('circle')
        .data(graphData.nodes)
        .enter().append('circle')
        .attr('class', 'node')
        .attr('r', 20)
        .attr('fill', d => nodeColors[d.label] || nodeColors.default)
        .attr('stroke', '#fff')
        .attr('stroke-width', 2)
        .call(d3.drag()
            .on('start', dragstarted)
            .on('drag', dragged)
            .on('end', dragended))
        .on('click', handleNodeClick)
        .on('dblclick', handleNodeDoubleClick);
    
    // 创建节点标签
    nodeLabels = svg.append('g')
        .attr('class', 'node-labels')
        .selectAll('text')
        .data(graphData.nodes)
        .enter().append('text')
        .attr('class', 'node-label')
        .attr('text-anchor', 'middle')
        .attr('dy', '.35em')
        .text(d => d.properties.name || d.label)
        .style('font-size', '12px')
        .style('fill', '#333')
        .style('pointer-events', 'none');
    
    // 创建连线标签
    linkLabels = svg.append('g')
        .attr('class', 'link-labels')
        .selectAll('text')
        .data(graphData.relationships)
        .enter().append('text')
        .attr('class', 'relationship-label')
        .attr('text-anchor', 'middle')
        .text(d => d.type)
        .style('font-size', '10px')
        .style('fill', '#666')
        .style('pointer-events', 'none');
    
    // 启动模拟
    simulation.nodes(graphData.nodes).on('tick', ticked);
    simulation.force('link').links(graphData.relationships);
    simulation.alpha(1).restart();
}

// 模拟tick事件
function ticked() {
    link
        .attr('x1', d => d.source.x)
        .attr('y1', d => d.source.y)
        .attr('x2', d => d.target.x)
        .attr('y2', d => d.target.y);
    
    node
        .attr('cx', d => d.x)
        .attr('cy', d => d.y);
    
    nodeLabels
        .attr('x', d => d.x)
        .attr('y', d => d.y);
    
    linkLabels
        .attr('x', d => (d.source.x + d.target.x) / 2)
        .attr('y', d => (d.source.y + d.target.y) / 2);
}

// 拖拽事件
function dragstarted(event, d) {
    if (!event.active) simulation.alphaTarget(0.3).restart();
    d.fx = d.x;
    d.fy = d.y;
}

function dragged(event, d) {
    d.fx = event.x;
    d.fy = event.y;
}

function dragended(event, d) {
    if (!event.active) simulation.alphaTarget(0);
    d.fx = null;
    d.fy = null;
}

// 节点点击事件
function handleNodeClick(event, d) {
    showNodeDetails(d);
    selectedNodes = [d];
    
    // 高亮选中的节点
    node.attr('stroke', n => n.id === d.id ? '#667eea' : '#fff')
        .attr('stroke-width', n => n.id === d.id ? 4 : 2);
}

// 节点双击事件
function handleNodeDoubleClick(event, d) {
    if (selectedNodes.length === 1 && selectedNodes[0].id !== d.id) {
        showAddRelationshipModal(selectedNodes[0], d);
    }
}

// 搜索节点
async function searchNodes() {
    const searchTerm = document.getElementById('searchInput').value.trim();
    
    if (!searchTerm) {
        showNotification('请输入搜索关键词', 'info');
        return;
    }
    
    try {
        const response = await fetch(`/api/graph/search?q=${encodeURIComponent(searchTerm)}`);
        const result = await response.json();
        
        if (result.success) {
            highlightSearchResults(result.data);
            showNotification(`找到 ${result.data.length} 个匹配节点`, 'success');
        } else {
            throw new Error(result.message || '搜索失败');
        }
    } catch (error) {
        console.error('搜索失败:', error);
        showNotification('搜索失败: ' + error.message, 'error');
    }
}

// 高亮搜索结果
function highlightSearchResults(searchResults) {
    const matchedIds = searchResults.map(result => result.n.id);
    
    node.attr('fill', d => {
        if (matchedIds.includes(d.id)) {
            return '#00ff00'; // 绿色高亮搜索结果
        }
        return nodeColors[d.label] || nodeColors.default;
    });
    
    // 3秒后恢复原始颜色
    setTimeout(() => {
        node.attr('fill', d => nodeColors[d.label] || nodeColors.default);
    }, 3000);
}

// 显示节点详情
function showNodeDetails(node) {
    const detailsContainer = document.getElementById('nodeDetails');
    
    let html = `
        <div class="node-info">
            <h4>${node.label} (ID: ${node.id})</h4>
            <div class="node-properties">
    `;
    
    Object.entries(node.properties).forEach(([key, value]) => {
        html += `
            <div class="node-property">
                <span class="property-key">${key}:</span>
                <span class="property-value">${value}</span>
            </div>
        `;
    });
    
    html += `
            </div>
            <div style="margin-top: 1rem;">
                <button class="btn btn-danger btn-sm" onclick="deleteNode(${node.id})">
                    删除节点
                </button>
            </div>
        </div>
    `;
    
    detailsContainer.innerHTML = html;
}

// 更新统计信息
function updateStats() {
    document.getElementById('nodeCount').textContent = graphData.nodes.length;
    document.getElementById('relationshipCount').textContent = graphData.relationships.length;
}

// 窗口大小调整
function handleResize() {
    const container = document.getElementById('graph');
    const rect = container.parentElement.getBoundingClientRect();
    width = rect.width;
    height = rect.height;
    
    svg.attr('width', width).attr('height', height);
    simulation.force('center', d3.forceCenter(width / 2, height / 2));
    simulation.alpha(1).restart();
}

// 显示/隐藏加载动画
function showLoading(show) {
    const loading = document.getElementById('loading');
    loading.style.display = show ? 'block' : 'none';
    loading.classList.toggle('hidden', !show);
}

// 显示通知
function showNotification(message, type = 'info') {
    const notification = document.getElementById('notification');
    notification.textContent = message;
    notification.className = `notification ${type}`;
    notification.classList.add('show');
    
    setTimeout(() => {
        notification.classList.remove('show');
    }, 3000);
}

// 初始化示例数据
async function initSampleData() {
    try {
        const response = await fetch('/api/graph/init-sample-data', {
            method: 'POST'
        });
        const result = await response.json();
        
        if (result.success) {
            showNotification('示例数据初始化成功', 'success');
            loadGraphData();
        } else {
            throw new Error(result.message || '初始化失败');
        }
    } catch (error) {
        console.error('初始化示例数据失败:', error);
        showNotification('初始化示例数据失败: ' + error.message, 'error');
    }
}

// 执行Cypher查询
async function executeCypherQuery() {
    const query = document.getElementById('cypherQuery').value.trim();
    
    if (!query) {
        showNotification('请输入Cypher查询语句', 'info');
        return;
    }
    
    try {
        const response = await fetch('/api/graph/query', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ cypher: query })
        });
        
        const result = await response.json();
        
        if (result.success) {
            displayQueryResult(result.data);
            showNotification('查询执行成功', 'success');
        } else {
            throw new Error(result.message || '查询执行失败');
        }
    } catch (error) {
        console.error('查询执行失败:', error);
        showNotification('查询执行失败: ' + error.message, 'error');
    }
}

// 显示查询结果
function displayQueryResult(data) {
    const resultContainer = document.getElementById('queryResult');
    
    if (!data || data.length === 0) {
        resultContainer.innerHTML = '<p>查询无结果</p>';
        return;
    }
    
    let html = '<div class="query-results">';
    
    data.forEach((record, index) => {
        html += `<div class="query-record"><strong>记录 ${index + 1}:</strong><pre>${JSON.stringify(record, null, 2)}</pre></div>`;
    });
    
    html += '</div>';
    resultContainer.innerHTML = html;
}

// 删除节点
async function deleteNode(nodeId) {
    if (!confirm('确定要删除这个节点吗？这将同时删除相关的所有关系。')) {
        return;
    }
    
    try {
        const response = await fetch(`/api/graph/nodes/${nodeId}`, {
            method: 'DELETE'
        });
        
        const result = await response.json();
        
        if (result.success) {
            showNotification('节点删除成功', 'success');
            loadGraphData();
            document.getElementById('nodeDetails').innerHTML = '<p class="placeholder">点击节点查看详情</p>';
        } else {
            throw new Error(result.message || '删除节点失败');
        }
    } catch (error) {
        console.error('删除节点失败:', error);
        showNotification('删除节点失败: ' + error.message, 'error');
    }
}

// 添加以下新函数到app.js文件末尾

// 显示设置模态框
function showSettingsModal() {
    // 加载当前设置
    loadCurrentSettings();
    document.getElementById('settingsModal').style.display = 'block';
}

// 关闭设置模态框
function closeSettingsModal() {
    document.getElementById('settingsModal').style.display = 'none';
    document.getElementById('connectionTestResult').style.display = 'none';
}

// 获取设置对象
function getSettings() {
    return JSON.parse(localStorage.getItem('neo4jSettings') || '{}');
}

// 加载当前设置
function loadCurrentSettings() {
    const settings = getSettings();
    
    document.getElementById('neo4jUrl').value = settings.url || 'bolt://localhost:7687';
    document.getElementById('neo4jUsername').value = settings.username || 'neo4j';
    document.getElementById('neo4jPassword').value = settings.password || '';
    document.getElementById('neo4jDatabase').value = settings.database || 'neo4j';
    
    updateConnectionStatus();
}

// 保存设置
async function saveSettings(event) {
    event.preventDefault();
    
    const settings = {
        url: document.getElementById('neo4jUrl').value.trim(),
        username: document.getElementById('neo4jUsername').value.trim(),
        password: document.getElementById('neo4jPassword').value,
        database: document.getElementById('neo4jDatabase').value.trim() || 'neo4j'
    };
    
    // 验证输入
    if (!settings.url || !settings.username || !settings.password) {
        showNotification('请填写完整的连接信息', 'error');
        return;
    }
    
    try {
        // 保存到本地存储
        localStorage.setItem('neo4jSettings', JSON.stringify(settings));
        
        // 发送到服务器更新配置
        const response = await fetch('/api/settings/neo4j', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(settings)
        });
        
        const result = await response.json();
        
        if (result.success) {
            showNotification('Neo4j设置保存成功', 'success');
            closeSettingsModal();
            updateConnectionStatus();
            // 重新加载数据以测试新连接
            loadGraphData();
        } else {
            throw new Error(result.message || '保存设置失败');
        }
    } catch (error) {
        console.error('保存设置失败:', error);
        showNotification('保存设置失败: ' + error.message, 'error');
    }
}

// 测试连接
async function testConnection() {
    const resultDiv = document.getElementById('connectionTestResult');
    const settings = {
        url: document.getElementById('neo4jUrl').value.trim(),
        username: document.getElementById('neo4jUsername').value.trim(),
        password: document.getElementById('neo4jPassword').value,
        database: document.getElementById('neo4jDatabase').value.trim() || 'neo4j'
    };
    
    if (!settings.url || !settings.username || !settings.password) {
        resultDiv.className = 'connection-test-result error';
        resultDiv.textContent = '请填写完整的连接信息';
        return;
    }
    
    resultDiv.className = 'connection-test-result testing';
    resultDiv.textContent = '正在测试连接...';
    
    try {
        const response = await fetch('/api/settings/test-connection', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(settings)
        });
        
        const result = await response.json();
        
        if (result.success) {
            resultDiv.className = 'connection-test-result success';
            resultDiv.textContent = `连接成功！数据库版本: ${result.version || '未知'}`;
        } else {
            resultDiv.className = 'connection-test-result error';
            resultDiv.textContent = `连接失败: ${result.message || '未知错误'}`;
        }
    } catch (error) {
        resultDiv.className = 'connection-test-result error';
        resultDiv.textContent = `连接失败: ${error.message}`;
    }
}

// 更新连接状态显示
function updateConnectionStatus() {
    const settings = getSettings();
    const statusElement = document.getElementById('connectionStatus');
    const urlElement = document.getElementById('currentDbUrl');
    
    if (settings.url) {
        urlElement.textContent = settings.url;
        statusElement.textContent = '已配置';
        statusElement.className = 'status-value connected';
    } else {
        urlElement.textContent = '未配置';
        statusElement.textContent = '未配置';
        statusElement.className = 'status-value disconnected';
    }
}



// 显示添加节点模态框
function showAddNodeModal() {
    document.getElementById('addNodeModal').style.display = 'block';
}

// 显示添加关系模态框
function showAddRelationshipModal(sourceNode, targetNode) {
    document.getElementById('sourceNodeInfo').textContent = `${sourceNode.properties.name || sourceNode.label} (ID: ${sourceNode.id})`;
    document.getElementById('targetNodeInfo').textContent = `${targetNode.properties.name || targetNode.label} (ID: ${targetNode.id})`;
    document.getElementById('sourceNodeId').value = sourceNode.id;
    document.getElementById('targetNodeId').value = targetNode.id;
    document.getElementById('addRelationshipModal').style.display = 'block';
}

// 创建节点
async function createNode(event) {
    event.preventDefault();
    
    const formData = new FormData(event.target);
    const nodeData = {
        label: formData.get('nodeLabel'),
        properties: {
            name: formData.get('nodeName'),
            description: formData.get('nodeDescription') || ''
        }
    };
    
    if (!nodeData.label || !nodeData.properties.name) {
        showNotification('请填写节点标签和名称', 'error');
        return;
    }
    
    try {
        const response = await fetch('/api/graph/nodes', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(nodeData)
        });
        
        const result = await response.json();
        
        if (result.success) {
            showNotification('节点创建成功', 'success');
            document.getElementById('addNodeModal').style.display = 'none';
            event.target.reset();
            loadGraphData();
        } else {
            throw new Error(result.message || '创建节点失败');
        }
    } catch (error) {
        console.error('创建节点失败:', error);
        showNotification('创建节点失败: ' + error.message, 'error');
    }
}

// 创建关系
async function createRelationship(event) {
    event.preventDefault();
    
    const formData = new FormData(event.target);
    const relationshipData = {
        sourceId: parseInt(formData.get('sourceNodeId')),
        targetId: parseInt(formData.get('targetNodeId')),
        type: formData.get('relationshipType'),
        properties: {
            description: formData.get('relationshipDescription') || ''
        }
    };
    
    if (!relationshipData.type) {
        showNotification('请填写关系类型', 'error');
        return;
    }
    
    try {
        const response = await fetch('/api/graph/relationships', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(relationshipData)
        });
        
        const result = await response.json();
        
        if (result.success) {
            showNotification('关系创建成功', 'success');
            document.getElementById('addRelationshipModal').style.display = 'none';
            event.target.reset();
            loadGraphData();
        } else {
            throw new Error(result.message || '创建关系失败');
        }
    } catch (error) {
        console.error('创建关系失败:', error);
        showNotification('创建关系失败: ' + error.message, 'error');
    }
}